package cn.tellsea.nacos;

import cn.tellsea.nacos.config.User;
import com.alibaba.cloud.nacos.NacosConfigManager;
import com.alibaba.nacos.api.config.listener.AbstractListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Bean;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.io.StringReader;
import java.util.Properties;

/**
 * nacos 分布式配置
 *
 * @author Tellsea
 * @date 2021/12/20
 */
@SpringBootApplication
@RestController
@RefreshScope
@EnableConfigurationProperties(User.class)
public class SpringCloudAlibabaNacosApplication {

    @Autowired
    private User user;
    @Autowired
    private NacosConfigManager nacosConfigManager;

    @Bean
    public ApplicationRunner runner() {
        return args -> {
            String dataId = "spring-cloud-alibaba-learn.properties";
            String group = "DEFAULT_GROUP";
            nacosConfigManager.getConfigService().addListener(dataId, group, new
                    AbstractListener() {
                        @Override
                        public void receiveConfigInfo(String configInfo) {
                            System.out.println("[Listener] " + configInfo);
                            System.out.println("[Before User] " + user);
                            Properties properties = new Properties();
                            try {
                                properties.load(new StringReader(configInfo));
                                String name = properties.getProperty("user.name");
                                int age = Integer.valueOf(properties.getProperty("user.age"));
                                user.setName(name);
                                user.setAge(age);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            System.out.println("[After User] " + user);
                        }
                    });
        };
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringCloudAlibabaNacosApplication.class, args);
    }

}
